/**
 * Created by shenyinlin on 2018/6/24.
 */
//初始化整个游戏的精灵，作为游戏开始的入口

import {ResourceLoader} from "./js/base/ResourceLoader.js";
import {Director} from "./js/Director.js";
import {BackGround} from "./js/runtime/BackGround.js";
import {DataStore} from "./js/base/DataStore.js";
import {Land} from "./js/runtime/Land.js";
import {Birds} from "./js/player/Birds.js";
import {StartButton} from "./js/player/StartButton.js";
import {Score} from "./js/player/Score.js";
import {ApiExamples} from "./js/ApiExamples.js";
import {ScoreItem} from "./js/player/ScoreItem.js"
import {HomeBackground} from "./js/player/HomeBackground.js";
import {FirstStudy} from "./js/player/FirstStudy.js";
import {OkButton} from "./js/player/OkButton.js";
import {PaiHangBtn} from "./js/player/PaiHangBtn.js";
import {PaiHangPage} from "./js/player/PaiHangPage.js";
import {Back} from "./js/player/Back.js";

import Request from './js/base/request.js';
import ServerUrl from './js/base/ServerUrl.js';


export class Main {


    constructor() {

        console.log('Main constructor..')

        // this.canvas = document.getElementById('game_canvas');

        this.canvas = wx.createCanvas();

        this.ctx = this.canvas.getContext('2d')

        // this.ctx = this.canvas.getContext('2d');

        this.dataStore = DataStore.getInstance();

        this.director = Director.getInstance();

        const loader = ResourceLoader.create();

        loader.onloaded(map => this.onResourceFirstLoaded(map));
    }

    onResourceFirstLoaded(map) {

        this.dataStore.canvas = this.canvas;

        //放到类变量,不put，有些变量是需要长期保留的,不需要长期保存的就put

        this.dataStore.ctx = this.ctx;

        this.dataStore.res = map;


        //从缓存中得知用户是否第一次玩。
        this.isFirstPlay = wx.getStorageSync('isFirstPlay');

        // console.log('this.isFirstPlay='+this.isFirstPlay);




        this.checkUserLogin();

        //调用初始化方法
        this.init();
    }

    //拿unioid
    getUnionId(code,userInfo) {
        const that = this
        const url = ServerUrl.platformManager + 'jscode2session'
        console.log('url:'+url)
        userInfo = JSON.parse(userInfo.toString())
        const data = {
            code: code,
            nickName:userInfo.nickName,
            gender:userInfo.gender,
            language:userInfo.language,
            avatarUrl:userInfo.avatarUrl,
            appId:'wx7878d393f42db3df'

        }

        console.log('usefinfo'+userInfo)

        console.log(userInfo.nickName)

        Request.postRequest(url, data).then(function (result) {
            console.log('result:'+JSON.stringify(result));
            const openid = result.data.openid
            console.log('openid:'+openid)
            wx.setStorageSync('openid',openid);
        })
    }


    //判断用户是否已经登录过,本地是否有openids
    checkUserLogin() {
        //wx api 接口
        const apis = new ApiExamples();
        let openid = wx.getStorageSync('openid');
        console.log('openid=' + openid)
        let that = this
        if (openid === '' || openid == null) {

            //获取用户信息 TODO...
            apis.getUserInfo().then(
                function(userInfo){
                    that.doLogin().then(
                        function (code) {
                            console.log('get code:' + code);
                            that.getUnionId(code,userInfo);
                        }
                    )
                }
            );


        }
    }

    doLogin() {
        const that = this
        return new Promise(function (resolve, reject) {
            wx.login({
                success: function (loginok) {
                    console.log('>Login Over -> ' + JSON.stringify(loginok))
                    resolve(loginok.code);
                }
            })

        })


    }


    //初始化
    init() {

        //默认游戏没有失败(结束)
        this.director.isGameOver = false;


        //往数据库中put背景
        this.dataStore
            .put('homeBackground', HomeBackground)
            .put('paiHangPage', PaiHangPage)
            .put('paiHangBtn', PaiHangBtn)
            .put('firstStudy', FirstStudy)
            .put('okButton', OkButton)
            .put('pencils', [])
            .put('background', BackGround)
            .put('land', Land)
            .put('birds', Birds)
            .put('score', Score)
            .put('back', Back)
            // .put('startButton',StartButton)
            .put('scoreItem', ScoreItem)
            //默认没在看排行榜
            .put('paiHangShow', false)
            .put('gameIsStart', false);


        //用户第一次打开我们的游戏
        this.director.readyPage(this.isFirstPlay);


        this.registerEvent();
        //游戏准备完毕
        //playReady();
    }


    //游戏准备,可以正常开始飞行
    playReady() {

        //注册事件
        //this.registerEvent();

        //创建铅笔要在游戏逻辑运行之前
        this.director.createPencil();

        //调用导演单例且运行它的run开始游戏方法。
        this.director.run();
        //这个变量代表了游戏已经启动了
        this.dataStore.put('gameIsStart', true);

        this.director.playAudio();

    }


    //注册事件
    registerEvent() {
        wx.onTouchStart((res) => {


            // this.dataStore.put('scoreItemShow',false);


            //游戏是否已启动?
            let gameIsStart = DataStore.getInstance().get('gameIsStart');

            //用户在看排行榜
            let paiHangShow = DataStore.getInstance().get('paiHangShow');

            //用户在看分数结算面板?
            let scoreItemShow = DataStore.getInstance().get('scoreItemShow');


            console.log('paihang show :' + paiHangShow);

            //[e.touches[0].pageX, e.touches[0].pageY]
            let thouchX = res.touches[0].pageX;
            let thouchY = res.touches[0].pageY;

            console.log(thouchX)
            console.log(thouchY)


            //拿出ok 按钮所位于的 x(横) y(纵) 两轴的位置,
            let okButtonX = DataStore.getInstance().get('okButtonX');
            let okButtonY = DataStore.getInstance().get('okButtonY');
            //拿出ok 按钮的长宽
            let okBtnWidth = DataStore.getInstance().get('okBtnWidth');
            let okBtnHeight = DataStore.getInstance().get('okBtnHeight');


            //拿出排行 按钮所位于的 x(横) y(纵) 两轴的位置,
            let paiHangBtnX = DataStore.getInstance().get('paiHangBtnX');
            let paiHangBtnY = DataStore.getInstance().get('paiHangBtnY');
            //拿出排行 按钮的长宽
            let paiHangBtnWidth = DataStore.getInstance().get('paiHangBtnWidth');
            let paiHangBtnHeight = DataStore.getInstance().get('paiHangBtnHeight');


            // wx.setStorageSync('isFirstPlay',true);
            // ok btn 点击判断
            //如果事件位置在矩形区域中(判断是否第一次看说明) 并且游戏不再进行中 ,
            //并且不在看排行榜
            if (paiHangShow == false && gameIsStart !== true && thouchX >= okButtonX && thouchX <= okButtonX + okBtnWidth && thouchY >= okButtonY && thouchY <= okButtonY + okBtnHeight) {

                console.log('开始游戏按钮被点击');

                this.playReady();
            }


            if (paiHangShow == false && this.director.isGameOver && gameIsStart !== true) {
                this.dataStore.put('gameIsStart', false);
                //游戏已经终止,取消动画刷新
                cancelAnimationFrame(this.dataStore.get('timer'));
                //释放数据缓存
                this.dataStore.destory();
                //Gc回收
                wx.triggerGC();

                //音乐停掉啊
                this.director.stopAudio();

                console.log('游戏重新开始');

                this.init();

            } else {
                //马向上飞
                this.director.birdsEvent();
            }
            console.log('点击排行按钮想打开排行:scoreItemShow=' + scoreItemShow);
            console.log('scoreItemShow:' + scoreItemShow);
            console.log('paiHangShow:' + paiHangShow);
            console.log('gameIsStart:' + gameIsStart);


            //在观看排行时的点击
            if (paiHangShow == true && thouchX < 100 && thouchY < 100) {
                console.log('从排行榜点击返回');
                this.dataStore.put('paiHangShow', false);
                // this.dataStore.get('paiHangPage').hidden();
                this.dataStore.get('homeBackground').draw();
                this.dataStore.get('okButton').draw();
                this.dataStore.get('paiHangBtn').draw();
                this.dataStore.destory();
            }
            //排行按钮点击判断

            if (scoreItemShow == false && paiHangShow == false && gameIsStart !== true &&
                thouchX >= paiHangBtnX &&
                thouchX <= paiHangBtnX + paiHangBtnWidth && thouchY >= paiHangBtnY && thouchY <= paiHangBtnY + paiHangBtnHeight) {

                console.log('条件满足,准备加载排行榜paiHangShow=' + paiHangShow);

                const that = this
                const url = ServerUrl.platformManager + 'topList'

                Request.postRequest(url, null).then(function (result) {
                    console.log('result:'+JSON.stringify(result));
                    let topList = result.data;
                    that.dataStore.get('paiHangPage').drawRow(topList);
                })

                this.dataStore.get('paiHangPage').draw();
                // console.log('排行页面刷出');
                this.dataStore.put('paiHangShow', true);


            }


            this.dataStore.put('scoreItemShow', false);

        });


    }


}